package com.wman.sheep.mvp.base;

import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wman.sheep.R;
import com.wman.sheep.adapter.EmptyAdapter;
import com.wman.sheep.common.application.AbsAppConfig;
import com.wman.sheep.common.exception.BaseException;
import com.wman.sheep.mvp.base.backactivity.BaseBackActivity;
import com.wman.sheep.rvadapter.BaseQuickAdapter;
import com.wman.sheep.widget.refreshlayout.PullRefreshLayout;

import java.util.ArrayList;

import androidx.recyclerview.widget.RecyclerView;

/**
 * 下拉列表界面基类
 */
public abstract class BaseListActivity<T extends BaseQuickAdapter, K>
        extends BaseBackActivity<ActivityPullListDelegate>
        implements BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, PullRefreshLayout.OnRefreshListener {

    protected T mAdapter;
    protected RecyclerView mRecyclerView;
    protected PullRefreshLayout mRecyclerRefreshLayout;
    protected FrameLayout mBottomLayout;
    protected View notDataView;

    /**
     * 延时时间
     */
    protected int delayMillis = 200;
    /**
     * 当前页数
     */
    public int mPage = AbsAppConfig.SAMPLE_START_PAGE;
    /**
     * 数据集
     */
    protected ArrayList<K> mDatas = new ArrayList<>();
    private TextView tvError;
    private ImageView ivError;

    @Override
    protected Class<ActivityPullListDelegate> getDelegateClass() {
        return ActivityPullListDelegate.class;
    }

    @Override
    protected void bindEventListener() {
        mRecyclerView = mViewDelegate.get(R.id.recyclerView);
        mRecyclerRefreshLayout = mViewDelegate.get(R.id.refreshlayout);
        mBottomLayout = mViewDelegate.get(R.id.fl_bottom_view);

        initNoDataViewState();
        initAdapter();

        mRecyclerRefreshLayout.setOnRefreshListener(this);
        mRecyclerRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);

        addHeadView();

        mPage = AbsAppConfig.SAMPLE_START_PAGE;
        onRefresh();

        initViewData();
    }

    protected void initNoDataViewState() {
        notDataView = getLayoutInflater().inflate(R.layout.view_empty_layout,
                (ViewGroup) mRecyclerView.getParent(), false);
        tvError = (TextView) notDataView.findViewById(R.id.tv_error_layout);
        ivError = (ImageView) notDataView.findViewById(R.id.img_error_layout);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        notDataView.setVisibility(View.GONE);
    }

    protected void initAdapter() {
        mAdapter = getAdapter();
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        // mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    public void setEmptyResource(int rid) {
        if (ivError != null) {
            ivError.setVisibility(View.VISIBLE);
            ivError.setImageResource(rid);
        }
    }

    public void setEmptyMsg(String tv) {
        if (tvError != null) {
            tvError.setText(tv);
        }
    }

    protected void addHeadView() {

    }

    protected void initViewData() {

    }

    /**
     * 获取BasePullUpRecyclerAdapter
     *
     * @return
     */
    protected abstract T getAdapter();

    /**
     * 网络数据的请求/处理
     */
    protected abstract void doRequest();

    @Override
    public void onRefresh() {
        getUiHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //数据未加载出来再次进行刷新操作需要判空处理
                if (mRecyclerView != null) {
                    mRecyclerView.scrollToPosition(0);
                }
                if (mAdapter != null) {
                    mAdapter.setNewData(mDatas);
                    mAdapter.setEnableLoadMore(false);
                    //检查是否满一屏，如果不满足关闭loadMore
                    mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
                }

                if (mAdapter instanceof EmptyAdapter) {

                } else {
                    if (mAdapter.getHeaderLayoutCount() <= 0 && mAdapter.getFooterLayoutCount() <= 0 && notDataView != null) {
                        mAdapter.setEmptyView(notDataView);
                    }
                }

                mPage = AbsAppConfig.SAMPLE_START_PAGE;
                showRefreshing();
                doRequest();
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        getUiHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doRequest();
            }
        }, delayMillis);
    }

    /**
     * 检查adapter的状态 是否加载更多
     *
     * @param nextIndex 下一页的页数
     */
    protected void checkAdapterLoadMoreStatus(final int nextIndex) {
        checkDataStatus();
        if (nextIndex > mPage) {
            mPage = nextIndex;
            //设置加载完成
            mAdapter.setEnableLoadMore(true);
            mAdapter.loadMoreComplete();
        } else if (mPage == AbsAppConfig.SAMPLE_START_PAGE && nextIndex < mPage) {
            mAdapter.setEnableLoadMore(false);
        } else {
            mAdapter.loadMoreEnd();
        }
    }

    /**
     * 检查adapter的状态 是否加载更多
     *
     * @param nextIndex 下一页的页数
     * @param dataSize  请求数据的数量
     */
    protected void checkAdapterLoadMoreStatus(final int nextIndex, final int dataSize) {
        if (dataSize < AbsAppConfig.SAMPLE_LIMIT) {
            checkAdapterLoadMoreStatus(0);
        } else {
            checkAdapterLoadMoreStatus(nextIndex);
        }
    }

    /**
     * 检查adapter的状态 是否加载更多
     *
     * @param nextIndex 下一页的页数
     * @param dataSize  实际请求数据的数量
     * @param limit     默认请求数据的数量
     */
    protected void checkAdapterLoadMoreStatus(final int nextIndex, final int dataSize, final int limit) {
        if (limit <= 0) {
            checkAdapterLoadMoreStatus(nextIndex, dataSize);
        } else {
            if (dataSize < limit) {
                checkAdapterLoadMoreStatus(0);
            } else {
                checkAdapterLoadMoreStatus(nextIndex);
            }
        }
    }

    /**
     * 刷新的时候数据源不为空清除数据
     */
    private void checkDataStatus() {
        if (mPage == AbsAppConfig.SAMPLE_START_PAGE) {
            if (mDatas != null && mDatas.size() > 0) {
                mDatas.clear();
            }
        }
    }

    /**
     * 设置底部view
     *
     * @param view
     * @param isShow
     */
    protected void setShowBottomLayout(View view, boolean isShow) {
        if (view == null) {
            new BaseException("不接收空对象...");
            return;
        }

        mBottomLayout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        mBottomLayout.removeAllViews();
        mBottomLayout.addView(view);

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mRecyclerRefreshLayout.getLayoutParams();
        lp.setMargins(0, 0, 0, isShow ? view.getLayoutParams().height : 0);
        mRecyclerRefreshLayout.setLayoutParams(lp);
    }

    /**
     * 显示加载进度条
     */
    public void showRefreshing() {
        if (mRecyclerRefreshLayout == null) {
            return;
        }

        mRecyclerRefreshLayout.setRefreshing(true);
    }

    /**
     * 关闭加载进度条
     */
    public void closeRefreshing() {
        if (mRecyclerRefreshLayout == null) {
            return;
        }

        getUiHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRecyclerRefreshLayout.setRefreshing(false);
            }
        }, 1000);

        if (mPage == AbsAppConfig.SAMPLE_START_PAGE && mDatas.size() == 0) {
            notDataView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置是否能刷新
     *
     * @param isCan
     */
    public void isCanRefresh(boolean isCan) {
        if (mRecyclerRefreshLayout == null) {
            return;
        }

        mRecyclerRefreshLayout.setCanRefresh(isCan);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }
}